import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:travel/extensions/date.dart';
import 'package:travel/routes/index.dart';
import 'package:travel/ui/draw_under_line.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';
import 'package:travel/screen/flutter_screenutil.dart';

class PaySafetyController extends GetxController {
  RxInt timeout = (2 * 3600 - 1).obs;

  List<_PayTypeModel> types = [];

  RxInt typeIndex = 0.obs;

  late Timer timer;

  @override
  void onInit() {
    types.add(_PayTypeModel(name: '支付宝支付', icon: 'u3870.svg'));
    types.add(_PayTypeModel(name: '微信支付', icon: 'u3871.svg'));
    types.add(_PayTypeModel(name: '建行龙支付', icon: 'u3873.svg'));
    types.add(_PayTypeModel(name: '招商银行一网通', icon: 'u3872.svg'));
    timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
      if (timeout.value == 0) {
        return this.timer.cancel();
      }
      timeout--;
    });
    super.onInit();
  }

  @override
  void onClose() {
    clearTimeout();
    super.onClose();
  }

  void clearTimeout() {
    if (timer.isActive) {
      timer.cancel();
    }
  }
}

class PaySafetyView extends GetView<PaySafetyController> {
  const PaySafetyView({super.key});

  @override
  Widget build(BuildContext context) {
    return Obx(() => Scaffold(
          backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF7f7),
          appBar: AppBar(
            automaticallyImplyLeading: true,
            backgroundColor: Colors.white,
            leading: InkWell(
              onTap: Get.back,
              child: Icon(
                Icons.arrow_back_ios,
                color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
                size: 20.w,
              ),
            ),
            leadingWidth: 40.w,
            title: Text(
              '安全支付',
              style: StylesUtils.customTextStyle(fontSize: 18.sp, color: ColorsUtils.color0000),
            ),
          ),
          body: SingleChildScrollView(
            child: Column(
              children: [
                Center(
                  child: Container(
                    margin: EdgeInsets.only(top: 15.h),
                    width: 345,
                    height: 100,
                    padding: const EdgeInsets.only(top: 20),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(8.w),
                        border: Border.all(color: ColorsUtils.rgb(252, 252, 252))),
                    child: Column(
                      children: [
                        Container(
                          height: 50,
                          alignment: Alignment.center,
                          child: Text.rich(TextSpan(children: [
                            TextSpan(
                                text: '￥',
                                style: StylesUtils.customTextStyle(
                                    color: ColorsUtils.color0000,
                                    fontSize: 22.sp,
                                    fontWeight: FontWeight.w700)),
                            TextSpan(
                                text: '60.00',
                                style: StylesUtils.customTextStyle(
                                    fontWeight: FontWeight.w700,
                                    fontSize: 36.sp,
                                    color: ColorsUtils.color0000))
                          ])),
                        ),
                        Center(
                            child: Text.rich(TextSpan(children: [
                          TextSpan(
                              text: '剩余时间：',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color7979, fontSize: 13.sp)),
                          TextSpan(
                            text: controller.timeout > 0
                                ? _durationTransform(controller.timeout.value)
                                : '已超时',
                            style: StylesUtils.customTextStyle(
                                fontSize: 13.sp, color: ColorsUtils.color6799),
                          ),
                        ])))
                      ],
                    ),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 10.h),
                  alignment: Alignment.center,
                  child: Container(
                    width: 345,
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(8.w),
                        border: Border.all(color: ColorsUtils.rgb(252, 252, 252))),
                    child: Column(
                      children: [
                        DrawUnderLine(
                          color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF5f5),
                          child: Container(
                            alignment: Alignment.centerLeft,
                            padding: EdgeInsets.symmetric(vertical: 15.h, horizontal: 15.w),
                          ),
                        ),
                        ListBody(
                            children: controller.types
                                .asMap()
                                .map((index, row) {
                                  Widget r = Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Center(
                                        child: ToolsUtils.assetImageSvg(row.icon,
                                            width: 28.w, height: 28.h),
                                      ),
                                      Expanded(
                                          child: Container(
                                        padding: EdgeInsets.only(left: 10.w),
                                        alignment: Alignment.centerLeft,
                                        child: Text(
                                          row.name,
                                          style: StylesUtils.customTextStyle(
                                              color: ColorsUtils.color3333, fontSize: 15.sp),
                                        ),
                                      )),
                                      Center(
                                        child: activeTypeChild(index),
                                      )
                                    ],
                                  );
                                  Widget child = DrawUnderLine(
                                      child: Container(
                                    height: 50.h,
                                    padding: EdgeInsets.symmetric(horizontal: 15.w),
                                    child: r,
                                  ));
                                  if (index == controller.types.length - 1) {
                                    child = Container(
                                      height: 50.h,
                                      padding: EdgeInsets.symmetric(horizontal: 15.w),
                                      child: r,
                                    );
                                  }
                                  return MapEntry(
                                      index,
                                      InkWell(
                                        onTap: () {
                                          if (controller.typeIndex.value != index) {
                                            controller.typeIndex.value = index;
                                          }
                                        },
                                        child: child,
                                      ));
                                })
                                .values
                                .toList()),
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
          bottomNavigationBar: SafeArea(
            bottom: true,
            child: Container(
              height: 60,
              alignment: Alignment.center,
              child: FractionallySizedBox(
                widthFactor: 0.85,
                heightFactor: 0.75,
                child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: ColorsUtils.rgba(226, 57, 64, 1),
                        borderRadius: BorderRadius.circular(10.w)),
                    child: TextButton(
                        onPressed: () {
                          controller.clearTimeout();
                          Get.toNamed(RoutePath.paySuccess);
                        },
                        child: Text.rich(TextSpan(children: [
                          TextSpan(
                              text: '立即支付 ', style: StylesUtils.customTextStyle(fontSize: 16.sp)),
                          TextSpan(text: '￥', style: StylesUtils.customTextStyle(fontSize: 13.sp)),
                          TextSpan(
                              text: '60.00', style: StylesUtils.customTextStyle(fontSize: 16.sp))
                        ])))),
              ),
            ),
          ),
        ));
  }

  String intlTime(int time) {
    DateFormat fmt = DateFormat('HH:mm:ss');
    return fmt.format(DateTime.fromMillisecondsSinceEpoch(Duration(seconds: time).inMilliseconds));
  }

  ///时间转换 将秒转换为小时分钟
  String _durationTransform(int seconds) {
    return Duration(seconds: seconds).toZhString();
  }

  Widget activeTypeChild(int index) {
    return CircleAvatar(
      radius: 11.0,
      backgroundImage: controller.typeIndex.value == index
          ? ToolsUtils.assetImageIcon('u3877_selected.png')
          : ToolsUtils.assetImageIcon('u3877.png'),
      child: Text(
        '✔',
        style: StylesUtils.customTextStyle(),
      ),
    );
  }
}

class _PayTypeModel {
  String name;

  String icon;

  _PayTypeModel({required this.name, required this.icon});
}
